/*
   ------------------------------------------------------------------------------------------------------
                             通过mqtt消息控制mq135空气质量传感器&dht11温湿度传感器  
   在iot/mq135_out主题发送空气质量数据;iot/dht11_out_temp发送温度数据；iot/dht11_out_hum发送湿度数据
   订阅iot/mq135&dht11_in主题获取控制信息。当信息为‘air’时，发送一条当前空气质量数据；当信息为“air_on”时，
   每两秒发送一条数据；当信息为“air_off”时，结束数据发送循环。temp、hum同理。
   ------------------------------------------------------------------------------------------------------
*/

#include <ESP8266WiFi.h>
#include <PubSubClient.h>
#include "MQ135.h"
#include <DHT.h>
#define DHTPIN 13 //定义DHT11数据传输针脚
#define DHTTYPE DHT11
DHT dht(DHTPIN, DHTTYPE);//进行初始设置
extern int air_cont = 0;
extern int temp_cont = 0;
extern int hum_cont = 0;
const char* ssid = "***********";
const char* password = "***********";
const char* mqtt_server = "***********";
const int ANALOGPIN = 0;
MQ135 gasSensor = MQ135(ANALOGPIN);

WiFiClient espClient;
PubSubClient client(espClient);
long lastMsg = 0;
String air_str;
String hum_str;
String temp_str;
char msg[50];
int value = 0;

void setup_wifi() {
  delay(10);
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid);
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  randomSeed(micros());
  Serial.println("");
  Serial.println("WiFi connected");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());
}

void callback(char* topic, byte* payload, unsigned int length) {
  Serial.print("Message arrived [");
  Serial.print(topic);
  Serial.print("] ");
  String msgIN;
  for (int i = 0; i < length; i++) {
    msgIN += (char)payload[i];//将payload转换成String
  }
  Serial.print(msgIN);
  Serial.println();
  //----------------------------------------------------------------------
  if (msgIN == "air") {
    float ppm = gasSensor.getPPM();
    air_str = String(ppm);
    air_str.toCharArray(msg, air_str.length() + 1);
    Serial.print("Publish message: ");
    Serial.println(msg);
    client.publish("iot/mq135_out", msg);
  }
  //----------------------------------------------------------------------
  if (msgIN == "temp") {
    float temp = dht.readTemperature();//读温度，默认为摄氏度
    temp_str = String(temp);
    temp_str.toCharArray(msg, temp_str.length() + 1);
    Serial.print("Publish message: ");
    Serial.println(msg);
    client.publish("iot/dht11_out_temp", msg);
  }
  //----------------------------------------------------------------------
  if (msgIN == "hum") {
    float hum = dht.readHumidity();//读湿度
    hum_str = String(hum);
    hum_str.toCharArray(msg, hum_str.length() + 1);
    Serial.print("Publish message: ");
    Serial.println(msg);
    client.publish("iot/dht11_out_hum", msg);
  }
  //----------------------------------------------------------------------
  if (msgIN == "air_on")//控制持续发送air_str
  {
    air_cont = 1;
  }
  if (msgIN == "air_off")
  {
    air_cont = 0;
  }

//----------------------------------------------------------------------
  if (msgIN == "temp_on")//控制持续发送temp_str
  {
    temp_cont = 1;
  }
  if (msgIN == "temp_off")
  {
    temp_cont = 0;
  }

//----------------------------------------------------------------------
  if (msgIN == "hum_on")//控制持续发送hum_str
  {
    hum_cont = 1;
  }
  if (msgIN == "hum_off")
  {
   hum_cont = 0;
  }
}
//----------------------------------------------------------------------

void reconnect() {
  while (!client.connected()) {
    Serial.print("Attempting MQTT connection...");
    String clientId = "ESP8266Client-";
    clientId += String(random(0xffff), HEX);
    if (client.connect(clientId.c_str())) {
      Serial.println("connected");
      client.subscribe("iot/mq135&dht11_in");
    } else {
      Serial.print("failed, rc=");
      Serial.print(client.state());
      Serial.println(" try again in 5 seconds");
      delay(5000);
    }
  }
}

void setup() {
  pinMode(BUILTIN_LED, OUTPUT);     // Initialize the BUILTIN_LED pin as an output
  Serial.begin(115200);
  setup_wifi();
  client.setServer(mqtt_server, 1883);
  client.setCallback(callback);
}

void loop() {
  if (!client.connected()) {
    reconnect();
  }
  client.loop();
  long now = millis();
  
  if (air_cont == 1) {
    //if (now - lastMsg > 2000) {
     // lastMsg = now;
     // ++value;
      float ppm = gasSensor.getPPM();
      air_str = String(ppm);
      air_str.toCharArray(msg, air_str.length() + 1);
      Serial.print("Publish message: ");
      Serial.println(msg);
      client.publish("iot/mq135_out", msg);
    //}
  }
  //----------------------------------------------------------------------
  if (temp_cont == 1) {
    //if (now - lastMsg > 2000) {
     // lastMsg = now;
     // ++value;
      float temp = dht.readTemperature();//读温度，默认为摄氏度
      temp_str = String(temp);
      temp_str.toCharArray(msg, temp_str.length() + 1);
      Serial.print("Publish message: ");
      Serial.println(msg);
      client.publish("iot/dht11_out_temp", msg);
   // }
  }
  //----------------------------------------------------------------------
  if (hum_cont == 1) {
   // if (now - lastMsg > 2000) {
    //  lastMsg = now;
    //  ++value;
      float hum = dht.readHumidity();//读湿度
      hum_str = String(hum);
      hum_str.toCharArray(msg, hum_str.length() + 1);
      Serial.print("Publish message: ");
      Serial.println(msg);
      client.publish("iot/dht11_out_hum", msg);
   // }
  }
  delay(2000);
}
